<template>
    <el-upload class="avatar-uploader" :show-file-list="false" :on-success="handleAvatarSuccess"
        :before-upload="beforeAvatarUpload" :http-request="handleUpload">
        <img v-if="imageUrl" :src="imageUrl" class="avatar" />
        <el-icon v-else class="avatar-uploader-icon">
            <Plus />
        </el-icon>
    </el-upload>
</template>
  
<script lang="ts" setup>
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import Cloud from "leancloud-storage";
import type { UploadProps } from 'element-plus'
interface PropsType {
    modelValue?: string
}
const props = defineProps<PropsType>()

const emit = defineEmits<{
    (e: string, agr: string): void
}>()
const imageUrl = ref('')
function getBase64(img: any, callback: (agr: string | ArrayBuffer | null) => void) {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result));
    reader.readAsDataURL(img);
}

const handleAvatarSuccess: UploadProps['onSuccess'] = (_, uploadFile) => {
    imageUrl.value = URL.createObjectURL(uploadFile.raw!)
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    if (rawFile.type !== 'image/jpeg'&&rawFile.type !== 'image/png') {
        ElMessage.error('Avatar picture must be JPG format!')
        return false
    } else if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error('Avatar picture size can not exceed 2MB!')
        return false
    }
    return true
}
function handleUpload(info: any) {
    getBase64(info.file, (base64) => {
        // 拿到图片的base64
        // console.log(base64);
        // 后端操作
        let cloudFile = new Cloud.File("vue-school.png", { base64 }); //将本地base64编码转为LeanCLoud资源,必须传入对象键值对为base64
        // console.log(cloudFile);
        //触发leancloud的存储操作
        cloudFile.save().then((res: any) => {
            // console.log(res);
            // 得到图片的线上网址
            let { url } = res.attributes;
            // console.log(url);
            imageUrl.value = url;
            emit('update:modelValue', url);
        });
    })
}

if (props.modelValue) {
    imageUrl.value = props.modelValue
}
</script>
  
<style scoped>
.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>
  
<style>
.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}
</style>
  